package com.api.action.v2;

import com.admin.entity.Station;
import com.admin.entity.SystemApk;
import com.admin.entity.Terminal;
import com.admin.entity.Theme;
import com.admin.mapper.SystemApkMapper;
import com.admin.service.IStationService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.OssUpload;
import com.api.service.v1.TerminalApiService;
import com.api.service.v1.WelcomeApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@RestController("ThemeApiAction_v2")
@RequestMapping("/api/v2/")
public class ThemeApiAction {


    @Autowired
    private TerminalApiService terminalApiService;

    @Autowired
    private WelcomeApiService welcomeApiService;

    @Autowired
    private IStationService stationService;

    @Autowired
    private OssUpload ossUpload;

    @Autowired
    private SystemApkMapper systemApkMapper;

    @Value("${SERVER}")
    private String ECS_SERVER;

    @Value("${oss}")
    private boolean oss;

    @Value("${apk.upgrade.list}")
    private String apkUpgradeList;

    @RequestMapping("/getTheme")
    public JSONObject getTheme(String mac, String packageName, String versionCode) {
        if (mac == null || mac.trim().length() < 1) {
            return null;
        }

        Terminal t = terminalApiService.findTerminalByMac(mac);
        if (t != null) {
            if (versionCode != null && versionCode.equals(t.getTerminalVersionCode()) == false) {
                t.setTerminalVersionCode(versionCode);
                terminalApiService.updateById(t);
            }
        }
        Theme theme = terminalApiService.findThemeByMac(mac);
        Theme themeDefault = null;


        //桌面配置
        if (theme == null) {
            return null;
        }

       /* if (System.currentTimeMillis()>1640966400000L)
        {
            if (ECS_SERVER.startsWith("http://172."))
            {
                return null;
            }
        }*/

        String jsonString = theme.getThemeAuditAndroidAudited();
        //欢迎界面
        String welcomeString = theme.getThemeWelcomePageAndroidchecked();

        if (welcomeString == null) {
            themeDefault = terminalApiService.getDefaultTheme(packageName);
            if (themeDefault==null)
            {
                welcomeString = themeDefault.getThemeWelcomePageAndroidchecked();
            }
        }

        JSONObject jsonObjectWelcome = null;
        if (welcomeString!=null && versionCode!=null)
        {
            try {
                if (Float.parseFloat(versionCode)<25)
                {
                    jsonObjectWelcome = JSONObject.parseObject(welcomeString);
                    JSONObject jsonObjectPanel = jsonObjectWelcome.getJSONObject("panel");
                    JSONObject jsonObjectLEAD = jsonObjectPanel.getJSONObject("LEAD");
                    if (jsonObjectLEAD!=null)
                    { JSONArray   jsonArrayVideos  =  jsonObjectLEAD.getJSONArray("videos");
                    List listViedos  = new ArrayList();
                    for (int i=0;i<jsonArrayVideos.size();i++)
                    {
                        Object obj = jsonArrayVideos.get(i);
                        if (obj instanceof JSONObject){
                            JSONObject v = (JSONObject)obj;
                            String url = v.getString("url");
                            if (url!=null)
                            {
                                listViedos.add(url);
                            }
                        }
                    }
                        jsonObjectLEAD.put("videos",listViedos);
                    }


                }else{
                    jsonObjectWelcome = JSONObject.parseObject(welcomeString);
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            if (welcomeString!=null)
            {
                jsonObjectWelcome = JSONObject.parseObject(welcomeString);
            }
        }


        //服务器
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        List servers = welcomeApiService.getServers(mac);
        jsonObject.getJSONObject("data").put("SERVER", servers);
        //本地服务器
        Station station = terminalApiService.findStationByMac(mac);
        if (station != null) {
            String localServer = station.getStationLocalServerIp(); //直播服务器
            String vodServer  = station.getVodServerIp();// 点播服务器
           /* if (ECS_SERVER.startsWith("http://172.20.0.2")){
                localServer = "172.20.0.251:9090";
            }*/
            jsonObject.getJSONObject("data").put("Local-Server", localServer);
            jsonObject.getJSONObject("data").put("Vod-Server", vodServer);

        }


        jsonObject.put("data2", jsonObjectWelcome);

        //-------新增英文版 ------------------------------------
        String englishString = theme.getEnglishAndroidYes();
        if (englishString != null && englishString.trim().length() > 0) {
            try {
                JSONObject englishJsonObject = JSONObject.parseObject(englishString);
                JSONObject enObject = englishJsonObject.getJSONObject("data").getJSONObject("EN");
                jsonObject.getJSONObject("data").put("EN", enObject);
            } catch (Exception e) {
            }
        }
        //----------------------------------------------------

        //系统apk
        if (station != null) {
            Integer systemAPkID = station.getStationSystemUpdate();
            if (systemAPkID != null) {
                SystemApk systemApk = systemApkMapper.selectById(systemAPkID);
                String status = systemApk.getSystemApkStatus();
                if (systemApk != null && "启用".equals(status)) {
                    String url = systemApk.getSystemApkUrl() + "?md5=" + systemApk.getSystemApkMd5();
                    systemApk.setSystemApkUrl(url);
                    jsonObject.put("launcher", systemApk);
                }
            }
        }

        //天气
        JSONObject weather = new JSONObject();
        final String reg = "<div class=\"[^\"]*\">([^<]+)</div>\\s*<div class=\"divCurrentWeather\">\\s*<img class='pngtqico' align='absmiddle' src='([^\']+)' style='border:0;width:20px;height:20px'/>([^<]+)<span class=\"cc30 f1\">([^<]+)</span>～<span class=\"c390 f1\">([^<]+)</span>";
        weather.put("server","http://i.tianqi.com/index.php?c=code&id=1");
        weather.put("reg",reg);
        jsonObject.put("weather",weather);

        //要升级的apk列表
        jsonObject.put("apkUpgradeList",apkUpgradeList);

        return jsonObject;
    }


    @RequestMapping("/getThemeByStation")
    public JSONObject getTheme(String BH) {
        //根据站点编号（不是主键）获取站点对象
        Station station = stationService.selectStationByStationBH(BH);
        if (station == null) {
            return JSONObject.parseObject("{}");
        }

        //查出站点所有分组
        List<Theme> themes = stationService.getThemeByStation(station);

        //查可用服务器
        List servers = new ArrayList();
        if (oss && ossUpload.getUrl() != null) {
            servers.add(ossUpload.getUrl());
        }
        servers.add(ECS_SERVER);

        JSONObject jsonsServer = new JSONObject();
        jsonsServer.put("SERVER", servers);

        JSONObject root = new JSONObject();
        root.put("data", jsonsServer);
        JSONArray jsonArray = new JSONArray();
        if (themes != null) {
            for (Theme t : themes) {
                String jsonString = t.getThemeAuditAndroidAudited();
                String jsonStringEnglish = t.getEnglishAndroidYes();
                //欢迎界面
                String welcomeString = t.getThemeWelcomePageAndroidchecked();
                JSONObject jsonObject = new JSONObject();
                JSONObject jsonObjecTheme = JSONObject.parseObject(jsonString);
                try {
                    JSONObject jsonObjectWelcome = JSONObject.parseObject(welcomeString);
                    jsonObject.put("welcome", jsonObjectWelcome);
                } catch (Exception e) {

                }
                jsonObject.put("theme", jsonObjecTheme);

                try {
                    JSONObject jsonObjecThemeEnglishih = JSONObject.parseObject(jsonStringEnglish);
                    jsonObject.put("themeEnglish", jsonObjecThemeEnglishih);
                } catch (Exception e) {

                }
                jsonArray.add(jsonObject);

            }
            root.put("themes", jsonArray);
        }

        //系统apk
        if (station != null) {
            Integer systemAPkID = station.getStationSystemUpdate();
            if (systemAPkID != null) {
                SystemApk systemApk = systemApkMapper.selectById(systemAPkID);
                if (systemApk != null && "启用".equals(systemApk.getSystemApkStatus())) {



                    String url =  systemApk.getSystemApkUrl() + "?md5=" + systemApk.getSystemApkMd5().toLowerCase();
                    root.put("launcher", url);
                }
            }
        }




        return root;

    }


}
